import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';//引入http客户端
import { Observable } from 'rxjs/Observable';
import { catchError, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

const CONTACT_URL = '/ng_one/assets/contacts.json';//定义请求路径

let _contacts;

@Injectable()
export class ContactService {
  constructor(private http: HttpClient) {}//依赖注入

  getContactsData(opts?: any) {
    let source;
    if (Array.isArray(_contacts)) { //如果有数据就返回原来的数据
      source = of(_contacts); //将原始数据包装
      const data = source.pipe( //通过管道处理数据
          map((data) => this.filter(data,opts))
      );
      return  data;
    } else {
      return  this.http.request('get', CONTACT_URL)
          .pipe(map((data) => {
            _contacts = data
           return  this.filter(data, opts)
          }),catchError(this.handleError))//ajax请求数据
    }

  }

  getContactById(id) {
    id = parseInt(id, 10);
    return this.getContactsData({ id: id }); //获取一条数据
  }

  getCollections() {
    return this.getContactsData({ collection: 1 }); //获取收藏数据
  }

  addContact(obj: any = {}) {
    if (!Array.isArray(_contacts)) {
      console.error('请刷新重试');
      return;
    }
    obj.id = _contacts.length + 1;
    _contacts.push(obj); //添加一条数据
  }

  editContact(obj: any) {
    // tslint:disable-next-line:curly
    if (!obj) return;
    if (!Array.isArray(_contacts)) {
      console.error('请刷新重试');
      return;
    }
    let idx = -1;
    for (const one of _contacts) {
      idx++;
      if (one.id === obj.id) {
        _contacts[idx] = one; //编辑数据 根据id判断 复写数据
      }
    }
  }

  collectContact(obj: any = {}) {
    if (!Array.isArray(_contacts)) {
      console.error('请刷新重试');
      return;
    }
    for (const one of _contacts) {
      if (one.id === obj.id) {
        // tslint:disable-next-line:no-bitwise
        one.collection ^= 1; //收藏数据
        break;
      }
    }
  }

  filter(data, opts) { //过滤器 将数据加工
    // tslint:disable-next-line:curly
    if (!opts) return data;
    if (opts.id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === opts.id) {
          data = data[i]; //获取单条数据
        }
      }
    }
    if (opts.collection) {
      const temp: any = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].collection === opts.collection) {
          temp.push(data[i]);
        }
      }
      data = temp; //获取收藏
      // 数据
    }
    return data;
  }

  handleError(err: HttpErrorResponse) {
    let errMsg;
    if (err.error instanceof Error) {
      // 客户端错误或者网络异常，即连接还没传达到服务端
      errMsg = err.error.message;
    } else if (err.status) {
      // 服务端已经接收到请求，但返回非 200 的 HTTP 状态码
      errMsg = `${err.status} - ${err.statusText}，详细错误：${err.error}`;
    }
    console.error(errMsg); // 打印到控制台
    return Observable.throw(errMsg);
  }
}